package com.hongyun.tms.service.impl;

import com.hongyun.tms.common.dto.SysFileDTO;
import com.hongyun.tms.common.po.SysFilePO;
import com.hongyun.tms.mapper.SysFileMapper;
import com.hongyun.tms.service.SysFileService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Minio服务实现类
 */
@Service
public class SysFileServiceImpl implements SysFileService {

    /**
     * 日志组件
     **/
    @Resource
    private SysFileMapper sysFileMapper;

    /**
     * 保存文件上传明细
     * @param fileList 文件明细列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(List<SysFileDTO> fileList) {
        insert(fileList);
    }


    @Override
    public List<SysFileDTO> listByIds(List<Long> fileIds) {
        if (CollectionUtils.isEmpty(fileIds)) {
            return Collections.emptyList();
        }
        return sysFileMapper.listByIds(fileIds);
    }


    @Override
    public SysFilePO getFileById(Long id) {
        return sysFileMapper.getFileById(id);
    }

    /**
     * 新增附件
     * @param fileList
     */
    private int insert(List<SysFileDTO> fileList) {
        return fileList.stream().mapToInt(val -> sysFileMapper.insert(val)).sum();
    }

    /**
     * 删除附件
     * @param fileId
     * @param businessId
     * @return
     */
    @Override
    public int delete(Long fileId, Long businessId) {
        List<Long> filesIdList = new ArrayList<>();
        int count = 0;
        // 附件id为空 且业务主键不为空
        if(null == fileId && null != businessId){
            // 根据业务主键查询附件id
            filesIdList = sysFileMapper.selectFileIdListByBusinessId(businessId);
        }else{
            filesIdList.add(fileId);
        }

        if(filesIdList.size() > 0){
            // 删除业务附件中间表
            count = sysFileMapper.deleteBusinessFiles(filesIdList);
            count = sysFileMapper.deleteFiles(filesIdList);
        }


        return count;
    }

    /**
     * 删除附件
     * @param fileId
     * @return
     */
//    @Override
    public int deleteById(Long fileId) {
        int count = 0;
        //删除
        if(null == fileId ){
            count = sysFileMapper.deleteById(fileId);
        }
        return count;
    }

    /**
     * 用来兼容新增证件时，先上传图片时，还没生成证件的id
     *
     * @param file
     */
    @Override
    public void updateById(SysFilePO file) {
        sysFileMapper.updateById(file);
    }
}
